<?php

class CowryController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		);
	}

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('getcowrys','getcommons'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('addcowry','addcommons','publish'),
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    public function actionPublish(){
        $upload_handler = new UploadHandler(null,false);
        $uploadMessage = $upload_handler->post(false);

        Yii::trace(json_encode($uploadMessage));
        $images = array();
        $imagesThumbnail = array();
        foreach ($uploadMessage['files'] as $key => $value) {
            array_push($images, $value->url);
            if(empty($value->thumbnailUrl))
                array_push($imagesThumbnail, $value->url);
            else
                array_push($imagesThumbnail, $value->thumbnailUrl);
        }

        $cowry = new Cowry();
        $cowry->userid= CommonUtils::getUserId();;
        $cowry->uploadtime = time();
        // $cowry->$desc_field = $_POST['desc'];
        // $cowry->$name_field = $_POST['name'];
        $cowry->comment = $_POST['comment'];
        $cowry->images = $images;
        $cowry->thumbnails = $imagesThumbnail;
        // $cowry->buytime = $order->createtime;
        $cowry->save();
        echoToMobile("ok");
    }

    /**
     * 添加宝贝
     *
     * @param $oid
     */
    public function actionAddCowry($oid) {
        $local = CommonUtils::getLocal();
        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }

        $order = Order::model()->findByPk(new MongoId($oid));
        if ($order->userid!=CommonUtils::getUserId()
           || $order->status==_ORDER_STATE_EDIT
           || $order->status==_ORDER_STATE_PAID
           || $order->status==_ORDER_STATE_CANCEL) {
           echoToError(_ERROR_SYSTEM_NOALLOW,"您还没有对该订单进行支付。");
        }

        $upload_handler = new UploadHandler(null,false);
        $uploadMessage = $upload_handler->post(false);

        $images = array();
        $imagesThumbnail = array();
        foreach ($uploadMessage['files'] as $key => $value) {
            array_push($images, $value->url);
            array_push($imagesThumbnail, $value->thumbnailUrl);
        }

        $cowry = new Cowry();
        $cowry->userid= $order->userid;
        $cowry->orderid = (string)$order->_id;
        $cowry->gid = $order->goods;
        $cowry->uploadtime = time();
        $cowry->$desc_field = $_POST['desc'];
        $cowry->$name_field = $_POST['name'];
        $cowry->comment = $_POST['comment'];
        $cowry->images = $images;
        $cowry->thumbnails = $imagesThumbnail;
        $cowry->buytime = $order->createtime;
        $cowry->sales = $order->sales;
        $cowry->save();
        echoToMobile("ok");
    }

    /**
     * 获得宝贝
     * @param int $type
     * @param $uploadtime
     */
    public function actionGetCowrys($type=_COWRY_FIND_SELF,$uploadtime=-1) {

        //查
        $query = array(
            'limit'=>_LIMITED_PAGE_SIZE,
            'sort'=> array('uploadtime'=>EMongoCriteria::SORT_DESC),
            'select'=>array('comment','_id','images','thumbnails','uploadtime','userid'),
        );

        $qs = array();
        if ($type==_COWRY_FIND_SELF) {
            $qs['userid'] = array('=='=>CommonUtils::getUserId());
        } else {
            $qs['userid'] = array('!='=>CommonUtils::getUserId());
        }

        if ($uploadtime>-1) {
            $qs['uploadtime']=array('<'=>$uploadtime);
        }
        $query['conditions']=$qs;
        $cowrys = Cowry::model()->findAll($query);
        $result = array();
        foreach ($cowrys as $key => $value) {
            $item = array();
            $item['id'] = (string)$value['_id'];
            $item['comment'] =$value['comment'];
            $item['uploadtime'] =$value['uploadtime'];
            $item['images'] = $value['images'];
            $item['thumbnails'] = $value['thumbnails'];
            $user = UserInfo::model()->findByPk(new MongoId($value['userid']));
            if(!empty($user))
            {
                $item['icon'] = $user->icon;
                $item['nickname'] = $user->nickname;
            }
            $query = array(
                'conditions'=>array('cowry'=>array('==' => (string)$value['_id'], ))
            );
            $item['comments'] = CowryComment::model()->count($query);

           //  if ($type==_COWRY_FIND_SELF) {
           //     $item['nickname']= CommonUtils::getUser()['nickname'];
           //     $item['icon']= CommonUtils::getUser()['icon'];
           //  } else {
           //     $user = $this->getUser($value['userid']);
           //     $item['nickname']= $user->nickname;
           //     $item['icon']= $user->icon;
           // }
           // $item['prise'] = RedisCacheUtil::getPriseSum($value->gid);
           // $item['favorite']= RedisCacheUtil::getFavoriteSum($value->gid);
           array_push($result,$item);
        }

        echoToMobile($result);
    }
    // public function actionGetCowrys($type=_COWRY_FIND_SELF,$uploadtime=-1) {
    //     $local = CommonUtils::getLocal();
    //     if ($local==_LOCAL_ZN) {
    //         $desc_field ='desc_zn';
    //         $name_field = 'name_zn';
    //     } else {
    //         $desc_field ='desc_en';
    //         $name_field = 'name_en';
    //     }

    //     //查
    //     $query = array(
    //         'limit'=>_LIMITED_PAGE_SIZE,
    //         'sort'=> array('uploadtime'=>EMongoCriteria::SORT_DESC),
    //         'select'=>array($desc_field,$name_field,'_id','uploadtime','buytime','sales','userid','images','orderid'),
    //     );

    //     $qs = array();
    //     if ($type==_COWRY_FIND_SELF) {
    //         $qs['userid'] = array('=='=>CommonUtils::getUserId());
    //     } else {
    //         $qs['userid'] = array('!='=>CommonUtils::getUserId());
    //     }

    //     if ($uploadtime>-1) {
    //         $qs['uploadtime']=array('<'=>$uploadtime);
    //     }
    //     $query['conditions']=$qs;
    //     $cowrys = Cowry::model()->findAll($query);
    //     $result = array();
    //     foreach ($cowrys as $key => $value) {
    //         $item = array();
    //         $item['name'] =$value[$name_field];
    //         $item['desc'] =$value[$desc_field];
    //         $item['sales']= $this->getSales($value['sales']);
    //         if ($type==_COWRY_FIND_SELF) {
    //            $item['nickname']= CommonUtils::getUser()['nickname'];
    //            $item['icon']= CommonUtils::getUser()['icon'];
    //         } else {
    //            $user = $this->getUser($value['userid']);
    //            $item['nickname']= $user->nickname;
    //            $item['icon']= $user->icon;
    //        }
    //        $item['prise'] = RedisCacheUtil::getPriseSum($value->gid);
    //        $item['favorite']= RedisCacheUtil::getFavoriteSum($value->gid);
    //        array_push($result,$item);
    //     }
    //     if (!empty($cowrys)) {
    //     }
    //     echoToMobile($result);
    // }

    /**
     * 获得评论
     * @param $cowryid
     * @param $createtime
     */
    public function actionGetCommons($cowryid,$createtime=-1) {
        $resultArr = array();
        $local = CommonUtils::getLocal();

        $query['select'] =  array('content','userid','createtime');
        $query['limit'] = _LIMITED_PAGE_SIZE;
        $query['sort'] = array('createtime'=>EMongoCriteria::SORT_DESC);
        if ($createtime>0) {
            $query['conditions'] = array('cowry'=>array('=='=>$cowryid),'createtime'=>array('<'=>$createtime),'local'=>array('=='=>$local));
        } else {
            $query['conditions'] = array('cowry'=>array('=='=>$cowryid));
        }
        $result = CowryComment::model()->findAll($query);
        if (!empty($result) && count($result)>0) {
            $len = count($result);
            for($index=0;$index<$len;$index++) {
                $item = array();
                $item['content'] = $result[$index]['content'];
                $item['createtime'] = $result[$index]['createtime'];
                if (!empty($result[$index]['userid'])) {
                    $userinfo=$this->getUser($result[$index]['userid']);
                    $item['nickname'] = $userinfo->nickname;
                    $item['icon'] = $userinfo->icon;
                } else {
                    $item['nickname'] = "匿名用户";
                    $item['icon'] = "";
                }
                array_push($resultArr,$item);
            }
        }
        echoToMobile($resultArr);
    }

    /**
     * 添加宝贝评论
     */
    public function actionAddCommons() {
        $local = CommonUtils::getLocal();
        $cowry = new CowryComment();
        $cowry->cowry = $_POST['cowryid'];
        $cowry->createtime = time();
        $cowry->content =$_POST['content'];
        $cowry->local = $local;
        $cowry->userid = CommonUtils::getUserId();
        $cowry->save();
        echoToMobile("ok");

    }

    /**
     * 获得用户信息
     * @param $userid
     * @return EMongoDocument
     */
    private function getUser($userid) {
        $mongoid = new MongoId($userid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
        );
        return UserInfo::model()->find($query);
    }

    private function getSales($sales) {
       return Sales::model()->findByPk(new MongoId($sales));
    }
}